package com.why.wechat;

import com.google.gson.Gson;
import com.wechat.constants.WechatConstants;
import com.wechat.pojo.WechatUserInfo;
import com.wechat.process.message.WechatImageMessageProcess;
import com.wechat.process.message.WechatTextMessageProcess;
import com.wechat.utils.SignUtils;
import com.wechat.utils.WechatUtils;
import com.wechat.utils.XmlUtils;
import org.jdom.JDOMException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Properties;

/**
 * @author Administrator
 * @date 2017/12/29 0029
 */
@Controller
@Scope("prototype")
public class WechatController {

    /**
     * 消息自动回复方法
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/wechat/responseMsg")
    public void responseMsg(@RequestParam(name = "signature", required = false) String signature,
                            @RequestParam(name = "timestamp", required = false) String timestamp,
                            @RequestParam(name = "nonce", required = false) String nonce,
                            @RequestParam(name = "echostr", required = false) String echostr,
                            @RequestBody(required = false) String content,
                            HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        PrintWriter out = response.getWriter();
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        //微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        request.setCharacterEncoding("UTF-8");
        //在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        response.setCharacterEncoding("UTF-8");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        String openId = request.getParameter("openid");
        try {
            System.out.println("是否token验证==》"+isGet);
            //微信服务器验证时使用get方法请求的
            if (isGet) {
                // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
                if (SignUtils.checkSignature(signature, timestamp, nonce)) {
                    System.out.print("输出字符串==》"+echostr);
                    out.print(echostr);
                }else{
                    System.out.print("验证失败");
                }
            }

            if (!StringUtils.isEmpty(content)) {
                String xmlMsgType = XmlUtils.getElementTextByName(content, "MsgType");
                if (WechatConstants.XmlMsgType.TEXT.equals(xmlMsgType)) {
                    System.out.println("开始回复文本信息");
                    //处理用户回复文本事件
                    // String xmlMsgTextContent = "";
                    // xmlMsgTextContent = XmlUtils.getElementTextByName(content, "Content");
                    String responseText = "test";
                    WechatTextMessageProcess wechatTextMessageProcess = new WechatTextMessageProcess();
                    wechatTextMessageProcess.setOpenId(openId);
                    wechatTextMessageProcess.setResponseText(responseText);
                    wechatTextMessageProcess.autoReplyWechatMessage(out);

                  /*  WechatImageMessageProcess wechatImageMessageProcess = new WechatImageMessageProcess();
                    wechatImageMessageProcess.setOpenId(openId);
                    wechatImageMessageProcess.setMediaId("7WwdhXlPjsSOAv4mcy3AXwwvZ_sTGtKUfJFkHaP4g3_vbcPxvzJqQoIU6w-nGE4-");
                    wechatImageMessageProcess.autoReplyWechatMessage(out);*/

                } else if (WechatConstants.XmlMsgType.IMAGE.equals(xmlMsgType)) {
                    //处理用户回复图片事件
                } else if (WechatConstants.XmlMsgType.EVENT.equals(xmlMsgType)) {
                    //处理用户关注/取消关注公众号事件
                    String wechatEventType = XmlUtils.getElementTextByName(content, "Event");
                    if (WechatConstants.WechatEventType.SUBSCRIBE.equals(wechatEventType)) {
                        //处理用户关注微信公众号
                        String eventKey = XmlUtils.getElementTextByName(content, "EventKey");
                        if (!StringUtils.isEmpty(eventKey)) {
                            ////   带参二维码关注事件
                        } else {
                            //   不带参二维码关注事件
                        }
                    } else if (WechatConstants.WechatEventType.UNSUBSCRIBE.equals(wechatEventType)) {
                        //   用户取消关注公众号事件
                    } else if (WechatConstants.WechatEventType.CLICK.equals(wechatEventType)) {
                        //   微信底部菜单点击事件
                    } else if (WechatConstants.WechatEventType.VIEW.equals(wechatEventType)) {
                        //点击微信底部菜单访问某个访问事件
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 个人中心
     *
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @throws InterruptedException
     */
    @RequestMapping(value = "/wx/userCenter")
    public String hFiveRedirect(@RequestParam(name = "code", required = false) String code, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, InterruptedException {
        HttpSession session = request.getSession();
        WechatUserInfo wxUserInfo = WechatUtils.getWxUserInfoByCode(code);
        //可以将获取到的信息保存到cookie；可以从数据库获取其它信息
     /*   cookieSaveUnionid(wxUserInfo, response);
        TerminalUser terminalUser = getTerminalUser(wxUserInfo, request, session);
        if (!StringUtils.isEmpty(terminalUser)) {
            request.getSession().setAttribute("user_info", terminalUser);
            //跳转到个人中心
            return "redirect:" + properties.getProperty("url") + "hfive/personage_index";
        } else {
            return this.toBindingPhonePage(wxUserInfo, request, properties);
        }*/
        return null;
    }

   /* @RequestMapping("/wx/wechatJsConfig")
    @ResponseBody
    public String wechatJsConfig(@RequestParam(value = "url", required = true) String url) {
        Map<String, String> map = WechatUtils.getJsSignMap(WechatUtils.getJsApiTicket(), url);
        return new Gson().toJson(map);
    }*/

}
